BluetoothPeripheralManager PRO

Requires Scripting PRO

The BluetoothPeripheralManager API enables your device to act as a Bluetooth Low Energy (BLE) peripheral. It allows you to:

  • Advertise device name and service UUIDs
  • Add or remove services with characteristics
  • Handle read and write requests from central devices
  • Notify subscribed centrals of characteristic value changes
  • Manage connection parameters such as connection latency

This API is ideal for building custom sensor devices, BLE peripheral simulators, controllers, and similar use cases.


Core Status Property

isAdvertising: Promise<boolean>

Returns whether the device is currently advertising as a peripheral.

1const advertising = await BluetoothPeripheralManager.isAdvertising
2console.log(advertising ? "Advertising" : "Not advertising")

Advertising Control

startAdvertising(advertisementData: { localName?: string; serviceUUIDs?: string[] }): Promise<void>

Begins BLE advertising with optional device name and service UUIDs.

1await BluetoothPeripheralManager.startAdvertising({
2  localName: "MyPeripheral",
3  serviceUUIDs: ["1234", "ABCD"]
4})

stopAdvertising(): Promise<void>

Stops ongoing BLE advertising.

1await BluetoothPeripheralManager.stopAdvertising()

Service Management

addService(service): Promise<void>

Adds a service and its characteristics to the peripheral.

Parameters:

1{
2  uuid: string,
3  characteristics: Array<{
4    uuid: string,
5    properties: string[], // e.g., ["read", "notify"]
6    permissions: string[], // e.g., ["readable"]
7    value?: Data
8  }>
9}

Example:

1await BluetoothPeripheralManager.addService({
2  uuid: "180F",
3  characteristics: [
4    {
5      uuid: "2A19",
6      properties: ["read", "notify"],
7      permissions: ["readable"],
8      value: Data.fromIntArray([85]) // 85% battery
9    }
10  ]
11})

removeService(serviceUUID: string): Promise<void>

Removes a previously added service by its UUID.


removeAllServices(): Promise<void>

Removes all services added by the current script.


Event Handlers for Central Interaction

onRestoreState: ((state) => void) | null

Called when the system restores your script due to a background BLE session. Useful for restoring service and advertising state.

1BluetoothPeripheralManager.onRestoreState = (state) => {
2  console.log("Restored state. Services count:", state.services.length)
3}
1type RestoreState = {
2  services: BluetoothServiceInfo[]
3  advertisementData: BluetoothAdvertisementData
4}

onReadyToUpdateSubscribers: (() => void) | null

Called when the system's transmission queue is cleared and ready to send notifications again after a previous failure due to queue congestion.

1BluetoothPeripheralManager.onReadyToUpdateSubscribers = () => {
2  console.log("Ready to resend notifications")
3}

onReadCharacteristicValue: (characteristicId, offset, central) => Promise<{result, value}>

Invoked when a remote central requests to read a characteristic.

If not implemented, the system returns readNotPermitted.

1BluetoothPeripheralManager.onReadCharacteristicValue = async (id, offset, central) => {
2  if (id === "2A19") {
3    return {
4      result: BluetoothATTResponseCode.success,
5      value: Data.fromIntArray([85]) // battery level
6    }
7  }
8  return { result: BluetoothATTResponseCode.attributeNotFound }
9}

Signature:

1(
2  characteristicId: string,
3  offset: number,
4  central: {
5    id: string,
6    maximumUpdateValueLength: number
7  }
8) => Promise<{
9  result: BluetoothATTResponseCode,
10  value?: Data | null
11}>

onWriteCharacteristicValue: (characteristicId, offset, value, central) => Promise<BluetoothATTResponseCode>

Invoked when a remote central attempts to write to a characteristic.

If not implemented, the system returns writeNotPermitted.

1BluetoothPeripheralManager.onWriteCharacteristicValue = async (id, offset, value, central) => {
2  console.log(`Write request to ${id}:`, value.toIntArray())
3  if (id === "2A19") {
4    return BluetoothATTResponseCode.success
5  }
6  return BluetoothATTResponseCode.attributeNotFound
7}

Signature:

1(
2  characteristicId: string,
3  offset: number,
4  value: Data,
5  central: {
6    id: string,
7    maximumUpdateValueLength: number
8  }
9) => Promise<BluetoothATTResponseCode>

onSubscribe: (characteristicId, central) => void

Called when a central subscribes to a characteristic that supports notifications or indications.

1BluetoothPeripheralManager.onSubscribe = (id, central) => {
2  console.log(`Central ${central.id} subscribed to ${id}`)
3}

onUnsubscribe: (characteristicId, central) => void

Called when a central unsubscribes from a characteristic.

1BluetoothPeripheralManager.onUnsubscribe = (id, central) => {
2  console.log(`Central ${central.id} unsubscribed from ${id}`)
3}

Notifications and Subscriptions

getSubscribers(characteristicId: string): Promise<Central[]>

Returns a list of central devices currently subscribed to a given characteristic.

Each item:

1{
2  id: string,
3  maximumUpdateValueLength: number
4}

updateValue(characteristicId: string, value: Data, options?): Promise<boolean>

Sends a notification or indication to all subscribed centrals (or a specified subset) with the updated characteristic value.

Returns:

  • true: Successfully sent
  • false: Queue is full — wait for onReadyToUpdateSubscribers before retrying

Connection Parameters

setDesiredConnectionLatency(centralId: string, latency): Promise<void>

Sets the preferred connection latency for a specific central device.

  • "low" – Faster interaction, higher power usage
  • "medium" – Balanced
  • "high" – Lower power usage, less frequent interaction

BluetoothATTResponseCode Enumeration

Defines response codes for read/write operations:

Name Value Meaning
success 0 Operation succeeded
invalidHandle 1 Invalid handle
readNotPermitted 2 Read not permitted
writeNotPermitted 3 Write not permitted
invalidPdu 4 Invalid PDU
insufficientAuthentication 5 Not authenticated
requestNotSupported 6 Request not supported
invalidOffset 7 Invalid offset
insufficientAuthorization 8 Not authorized
prepareQueueFull 9 Prepare queue is full
attributeNotFound 10 Attribute not found
attributeNotLong 11 Attribute not long
insufficientEncryptionKeySize 12 Encryption key size too small
invalidAttributeValueLength 13 Invalid attribute value length
unlikelyError 14 Unlikely error occurred
insufficientEncryption 15 Encryption required
unsupportedGroupType 16 Unsupported group type
insufficientResources 17 Insufficient resources

Example: Broadcasting a Battery Service

1await BluetoothPeripheralManager.addService({
2  uuid: "180F",
3  characteristics: [
4    {
5      uuid: "2A19",
6      properties: ["read", "notify"],
7      permissions: ["readable"],
8      value: Data.fromIntArray([100]) // Battery level 100%
9    }
10  ]
11})
12
13await BluetoothPeripheralManager.startAdvertising({
14  localName: "BatteryPeripheral",
15  serviceUUIDs: ["180F"]
16})
17
18BluetoothPeripheralManager.onReadCharacteristicValue = async (id, offset, central) => {
19  return { result: BluetoothATTResponseCode.success, value: Data.fromIntArray([90]) }
20}